#include "stdafx.h"
#include "msgqueue/msgqueuemgr.h"
#include "render/rendermgr.h"
#include "./playerthread.h"

PlayerThread::PlayerThread()
: m_queueIndex(-1)
, m_player(NULL)
{	
}

PlayerThread::~PlayerThread()
{
	if (m_queueIndex != -1)
	{
		MsgQueueMgr::GetInstance().UnRegisterQueue<TankMsg>(m_queueIndex);
	}

	RenderMgr::GetInstance().OnBeforeRender -= EventObject<OnBeforeRenderFunc>(this, &PlayerThread::OnBeforeRender);

	delete m_player;
	m_player = NULL;
}

Player* PlayerThread::GetPlayer()
{
	return m_player;
}

void PlayerThread::Init(
	int id,
	string strName, 
	Point startPos, 
	float startAngle, 
	Point hpPos,
	float z,
	Color color)
{
	if (m_player)
	{
		m_player->OnDestroy -= EventObject<OnPlayerDestroyFunc>(this, &PlayerThread::OnPlayerDestroy);
		delete m_player;

		RenderMgr::GetInstance().OnBeforeRender -= EventObject<OnBeforeRenderFunc>(this, &PlayerThread::OnBeforeRender);
	}

	m_queueIndex = MsgQueueMgr::GetInstance().RegisterQueue<TankMsg>();
	m_player = new PlayerAI(id, strName, startPos, startAngle, hpPos, z, color);
	m_player->OnDestroy += EventObject<OnPlayerDestroyFunc>(this, &PlayerThread::OnPlayerDestroy);

	RenderMgr::GetInstance().OnBeforeRender += EventObject<OnBeforeRenderFunc>(this, &PlayerThread::OnBeforeRender);
}

void PlayerThread::OnBeforeRender(float differTime)
{
	TankMsg* pMsg = POPCLEAR_MSG_QUEUE(TankMsg, m_queueIndex);
	m_player->DoMsg(pMsg);
}

void PlayerThread::OnPlayerDestroy()
{
	//destroy thread and tank
	m_bStopEvent = true;
	m_player->Destroy();
	BaseThread::Stop();
}

void PlayerThread::ThreadFunc()
{
	while (true)
	{
		if (CheckStates())
		{
			break;
		}

		TankMsg msg;
		memset(&msg, 0, sizeof(msg));

		m_player->DoAI(&msg);

		PUSH_MSG_QUEUE(TankMsg, m_queueIndex, msg);

		Sleep(10);
	}
}